import express  from 'express';
import util from 'utility'
import jwt from 'jsonwebtoken';  
// 验证JWT令牌  
function verifyToken(req, res, next) {  
    const secretKey = 'qfdixon'; // 替换为你的密钥  
    const token = req.headers['authorization'];  
    if (!token) return res.sendStatus(401);  
    jwt.verify(token, secretKey, {
      maxAge: '1d'
    }, (err, user) => {  
      if (err) return res.sendStatus(403);  
      req.user = user;  
      next();  
    });  
  }  

const router = express.Router();  
function generateToken(user) {  
    const secretKey = 'qfdixon'; // 替换为你的密钥  
    return jwt.sign({ user }, secretKey, { expiresIn: '24h' });  
}  

// 司机登录注册 统一流程
router.post('/login',async(req,res)=>{
    const { phone ,code } = req.body;
    const exitsCode = req.nodeCache.get(`code_driver_${phone}`);
    if(code != exitsCode) return res.fail('验证码不正确')
    let user =await req.prisma.User.findFirst({
        where:{
            type:'driver',
            phone,
        }
    })
    if(!user){
        // 如果还没有注册就直接注册然后登录
        user = await req.prisma.User.create({
            data: {
                type: 'driver',
                phone,
            }
        })
        
        
    } 
    
    const token = generateToken(user);
    res.success({phone,token})

})


router.post('/acceptOrder', async(req,res)=>{
    const { orderId } = req.body;
    // const driver = req.user.user
    const driver = {uid:3};
    const order = await req.prisma.Order.findFirst({
        where:{
            id: orderId
        },
        include:{
            OrderCarTypes: true
        }
    })

    // todo 根据司机的id去查看他的车辆信息
    const carInfo = {
        carType: 'fast'
    }
    
    // 根据订单去计算价格
    const temCar = order.OrderCarTypes.find(item=>item.carType === carInfo.carType).fee*0.8

 
    // 如果订单已经被接了就不能再被接单
    if(order.status !== 'ordering'){
            return res.fail('订单异常 sorry')
    }
    

    await req.prisma.Order.update({
        where:{
            id: orderId
        },
        data:{
            driverId:  driver.uid,
            carType:  carInfo.carType,
            status: 'willArrive',
            takeTime: new Date(),
        }
    })

})


router.post('/addCar', verifyToken,async(req,res)=>{

        const { brandId , carno, color, vinPhoto}  = req.body;
        const user = req.user.user;
        await req.prisma.Car.create({
            data:{
                uid: user.id,
                brandId,
                color,
                carno,
                vinPhoto
            }
        })

        res.success('添加ok')
})

// 查询自己的车辆
router.get('/mycar',verifyToken, async(req,res)=>{
    const user = req.user['user'];
    const carInfo = await req.prisma.Car.findFirst({
        where:{
            uid:user['uid']
        },
        include:{
            driver: true,
            brand: true
        }
    })
    res.success(carInfo)
})

// 更新证件信息
router.post('/updateLicense',verifyToken, async (req,res)=>{
    const {dlfront , dlback, license , idfront,idback,realName,idNo} = req.body;
    const user = req.user.user;
    console.log('user',user)
    const updateData = {}
    if(dlfront) updateData.dlfront = dlfront;
    if(dlback)  updateData.dlback = dlback;
    if(license)  updateData.license = license;
    if(idback) updateData.idback = idback;
    if(idfront) updateData.idfront = idfront;
    if(realName) updateData.realName = realName;
    if(idNo) updateData.idNo = idNo

    try{
        await req.prisma.User.update({
            where:{
                id: user.id,
            },
            data: updateData
        })
    } catch(e){
        console.log(e)
    }
    
    res.success('ok')
})

router.get('/getMyLicense',verifyToken,async(req,res)=>{
    const user = req.user.user;
    const info = await req.prisma.User.findUnique({
        where:{
            id: user.id,
        },
        select:{
            dlfront: true,
            dlback: true,
            license: true,
            idNo: true,
            realName: true,
            idfront: true,
            idback: true
        }
        
    })
    res.success(info)
})


 // 司机到达目的点


 router.post('/arrive',async(req,res)=>{
    const { id } = req.body;
    // 需要确保处于等待接单或者是司机未到达的状态
    const order = await req.prisma.Order.findUnique({
        where:{
            id,
            status:'willArrive'
        },
      
    })
    if(!order) return res.fail('订单状态错误请查看');
    await req.prisma.Order.findUnique({
        where:{
            id
        },
        data:{
            status: 'arrived'
        }
    })

    res.success('确定成功')

})


router.post('/cancel',async(req,res)=>{
    const { id } = req.body;
    // 需要确保处于等待接单或者是司机未到达的状态
    const order = await req.prisma.Order.findUnique({
        where:{
            id,
            status:'willArrive' , // 司机只有在即将到达的时候可以取消订单
        },
      
    })
    if(!order) return res.fail('订单状态错误请查看');
    await req.prisma.Order.findUnique({
        where:{
            id
        },
        data:{
            status: 'driverCancel'
        }
    })
    // 需要通知客户订单取消了

    // 然后重新进入到订单流程

    res.success('取消成功成功')

})



export default  router;

